#!/bin/bash
# 安装为systemd系统服务

if [ "$EUID" -ne 0 ]; then 
    echo "❌ 请使用 sudo 运行此脚本"
    echo "sudo ./install_service.sh"
    exit 1
fi

echo "=========================================="
echo "安装定位后台系统服务"
echo "=========================================="
echo ""

# 获取当前目录的绝对路径
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
USER_NAME="${SUDO_USER:-$USER}"

echo "📁 安装目录: $SCRIPT_DIR"
echo "👤 运行用户: $USER_NAME"
echo ""

# 创建systemd服务文件
SERVICE_FILE="/etc/systemd/system/location-backend.service"

cat > $SERVICE_FILE << EOF
[Unit]
Description=Location Backend Service
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$SCRIPT_DIR
Environment="PATH=$SCRIPT_DIR/venv/bin:/usr/local/bin:/usr/bin:/bin"
ExecStart=$SCRIPT_DIR/venv/bin/python3 $SCRIPT_DIR/server.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

echo "✅ 服务文件已创建: $SERVICE_FILE"
echo ""

# 重新加载systemd
systemctl daemon-reload
echo "✅ systemd已重新加载"
echo ""

# 启用服务
systemctl enable location-backend.service
echo "✅ 服务已设置为开机自启"
echo ""

# 启动服务
systemctl start location-backend.service
echo "✅ 服务已启动"
echo ""

# 显示服务状态
echo "=========================================="
echo "服务状态："
echo "=========================================="
systemctl status location-backend.service --no-pager
echo ""

echo "=========================================="
echo "常用命令："
echo "=========================================="
echo "查看状态:   sudo systemctl status location-backend"
echo "启动服务:   sudo systemctl start location-backend"
echo "停止服务:   sudo systemctl stop location-backend"
echo "重启服务:   sudo systemctl restart location-backend"
echo "查看日志:   sudo journalctl -u location-backend -f"
echo "禁用自启:   sudo systemctl disable location-backend"
echo "=========================================="

